<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <script>

    function call(fn, thisObj, ...args) {
      if (thisObj===undefined || thisObj===null) {
        return this(...args)
        // thisObj = window
      }

      // const result = this(...args)
      // return result

      // 基本思路将当前函数添加为thisObj的方法, 通过thisObj来调用这个方法

      thisObj.tempFn = fn
      const result = thisObj.tempFn(...args)
      // 删除添加的方法
      delete thisObj.tempFn

      return result
    }

    // 立即调用当前函数, 并指定this对象
    Function.prototype.call = function (thisObj, ...args) {
      console.log('call')

      if (thisObj===undefined || thisObj===null) {
        return this(...args)
        // thisObj = window
      }

      // const result = this(...args)
      // return result

      // 基本思路将当前函数添加为thisObj的方法, 通过thisObj来调用这个方法

      thisObj.tempFn = this
      const result = thisObj.tempFn(...args)
      // 删除添加的方法
      delete thisObj.tempFn

      return result

    }

    Function.prototype.apply = function (thisObj, args) {
      console.log('apply')

      if (thisObj===undefined || thisObj===null) {
        return this(...args)
        // thisObj = window
      }
      // const result = this(...args)
      // return result

      // 基本思路将当前函数添加为thisObj的方法, 通过thisObj来调用这个方法

      thisObj.tempFn = this
      const result = thisObj.tempFn(...args)
      // 删除添加的方法
      delete thisObj.tempFn

      return result

    }

    

    // 对象快照: 打印对象时, 对象当时的样子
  </script>

  <script>
    // 返回一个新函数, 新函数内部会调用函数, 且指定this为bind的第一个参数对象
    // 原函数的实参, 优选考虑bind指定的参数, 其次考虑新函数调用指定的参数
    Function.prototype.bind = function (thisObj, ...args) {
      console.log('bind')
      return (...args2) => {
        return this.call(thisObj, ...args, ...args2)
      }
    }
  </script>

 
  <script>
    var m = 2
    function fn(a, b) {
      console.log(this, a, b);
      return a + b
    }
    const obj = {m: 1}

   
    // console.log(fn.call(obj, 3, 4))
    // console.log(fn.call(undefined, 3, 4))
    // console.log(fn.apply(obj, [3, 4]))
    
    // console.log(call(fn, obj, 3, 4))


    console.log(fn.bind(obj)(5, 6))
    console.log(fn.bind(obj, 7)(5, 6))
    console.log(fn.bind(obj, 7, 8)(5, 6))
    
    
  </script>
</body>
</html>